<script setup lang='ts'>
import { storeToRefs } from "pinia"
import { ref, reactive, nextTick, onMounted } from "vue";
import { useRouter } from "vue-router"
import type { TabsPaneContext, FormInstance } from 'element-plus'
import { ElMessage } from "element-plus"
import { useUserInfoStore } from "@/store/user"
import { menuStore } from "@/store/menu"
import { useColorStore } from "@/store/common"
import { logoutGetApi } from "@/api/login"
import { accountPasswordApiPut, accountSaveOrUpdateApiPost } from "@/api/userMangement"
const userStore = useUserInfoStore()
const provinceData = useColorStore()
const meStore = menuStore()
const { province, selectProvinceCity } = storeToRefs(provinceData)
const { filterData } = provinceData
const { userInfo } = storeToRefs(userStore)
const { clearUserInfo } = userStore
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const formSize = ref('default')

const newPassRef = ref()
const copyUserInfo = ref()

const activeName = ref('first')

const passWordForm = reactive({
  oldPassword: null,
  newPassword: null,
  newPasswordConfirm: null
})
onMounted(() => {
  copyUserInfo.value = JSON.parse(JSON.stringify(userInfo.value))
  setTimeout(() => {
    filterData(1, null, copyUserInfo.value.provinceCode)
  }, 4000);
})
const validate2 = async (rule: any, value: any, callback: any) => {

  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== passWordForm.newPassword) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }

}
const detailRules = reactive({
  provinceCode: [
    {
      required: true,
      trigger: 'blur',
      message: "请选择用户所在地-省"
    },
  ],
  cityCode: [
    {
      required: true,
      trigger: 'blur',
      message: "请选择用户所在地-市"
    },
  ],
  username: [
    {
      required: true,
      trigger: 'blur',
      message: "请输入用户姓名"
    },
    {
      pattern: /^[0-9a-z]*$/,
      message: "只能输入小写字母和数字"
    }
  ],
  nickname: [
    {
      required: true,
      trigger: 'blur',
      message: "请输入用户真实姓名"
    },
  ],
  email: [
    {
      required: true,
      trigger: 'blur',
      message: "请输入用户邮箱"
    },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱格式"
    }
  ],
  mobile: [
    {
      required: true,
      trigger: 'blur',
      message: "请输入用户手机号"
    },
    {
      trigger: 'blur',
      message: "请输入正确的手机号",
      pattern: /^1[3-9]\d{9}$/
    }
  ],
})
const passRules = reactive({
  oldPassword: [
    {

      required: true,
      trigger: 'blur',
      message: "请输入旧密码"
    }
  ],
  newPassword: [
    {

      required: true,
      trigger: 'blur',
      message: "请输入新密码"
    }
  ],
  newPasswordConfirm: [
    {

      required: true,
      trigger: 'blur',
      message: "请输入确认密码"
    },
    {
      asyncValidator: validate2,
      trigger: 'blur',
      required: true
    }
  ]
})
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

const submitForm = (formEl: FormInstance | undefined) => {
  console.log(formEl);
  if (!formEl) return
  formEl.validate(async isOk => {
    if (isOk) {
      try {
        const arr = {
          id: copyUserInfo.value.id,
          username: copyUserInfo.value.username,
          nickname: copyUserInfo.value.nickname,
          mobile: copyUserInfo.value.mobile,
          email: copyUserInfo.value.email,
          enabled: copyUserInfo.value.enabled,
          accountLocked: copyUserInfo.value.accountLocked,
          provinceCode: copyUserInfo.value.provinceCode,
          provinceName: copyUserInfo.value.provinceName,
          cityCode: copyUserInfo.value.cityCode,
          cityName: copyUserInfo.value.cityName,
          adress: copyUserInfo.value.adress,
          blurb: copyUserInfo.value.blurb,
        }
        const res = await accountSaveOrUpdateApiPost(arr)
        if (res.code == 20000) {
          await logoutGetApi()
          meStore.clearStrore()
          sessionStorage.clear()
          clearUserInfo()
          router.push("/login")
          ElMessage({
            type: "success",
            message: "用户基础数据修改成功"
          })
        }
      } catch (error) {

      }
    }
  })

}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  newPassRef.value.validate(async (isOk: boolean) => {
    console.log(isOk);
    if (isOk) {
      try {
        const res = await accountPasswordApiPut(passWordForm)
        if (res.code == 20000) {
          // newPassRest()
          await logoutGetApi()
          meStore.clearStrore()
          sessionStorage.clear()
          clearUserInfo()
          router.push("/login")
          ElMessage({
            type: "success",
            message: "密码修改成功"
          })
        }
      } catch (error) {

      }

    }

  })

}

const newPassRest = () => {
  newPassRef.value.resetFields()
}

const proChange = (val: any) => {
  console.log(val);
  province.value.some(item => {
    if (val == item.dictItemCode) {
      filterData(1, item.id)
      copyUserInfo.value.provinceName = item.dictItemName
      return
    }
  })

}
const proChange1 = (val: any) => {
  console.log(val);
  selectProvinceCity.value.some(item => {
    if (val == item.dictItemCode) {
      copyUserInfo.value.cityName = item.dictItemName
      return
    }
  })
}


</script>

<template>
  <div v-if="copyUserInfo">
    <el-card shadow="never" class="card-style">
      <div class="container">
        <!-- 响应式布局 1 2 3 -->
        <el-row :gutter="15" justify="space-around">
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" style="">
            <el-avatar :size="100" src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" />
          </el-col>
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8"
            style="display: flex;flex-direction: column;justify-content: center;height: 100px;line-height: 30px;">
            <div class="top">
              <span>用户账号 ：</span> <span>{{ copyUserInfo.username }}</span>
            </div>
            <div class="bottom">
              <span>用户姓名 ： </span> <span>{{ copyUserInfo.nickname }}</span>
            </div>
          </el-col>
          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8"   style="display: flex;flex-direction: column;justify-content: center;height: 100px;line-height: 30px;">
            <div class="top">
              <span>手机号码 ：</span> <span>{{ copyUserInfo.mobile }}</span>
            </div>
            <div class="bottom">
              <span>注册时间 ：</span> <span>{{ copyUserInfo.credentialsExpiredTime }}</span>
            </div>
          </el-col>

        </el-row>
        <!--      <div class="left">
          <el-avatar :size="100" src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" />
        </div>

        <div class="right">
          <el-row>
            <el-col :span="12">
              <span>用户账号 ：</span> <span>{{ copyUserInfo.username }}</span>
            </el-col>
            <el-col :span="12">
              <span>手机号码 ：</span> <span>{{ copyUserInfo.mobile }}</span> </el-col>
          </el-row>
          <el-row>
            <el-col :span="12"> <span>用户姓名 ： </span> <span>{{ copyUserInfo.nickname }}</span></el-col>
            <el-col :span="12"> <span>注册时间 ：</span> <span>{{ copyUserInfo.credentialsExpiredTime }}</span></el-col>
          </el-row>
        </div> -->
      </div>
    </el-card>
    <el-card shadow="never" class="card-style" style="margin-top: 10px;">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane name="first">
          <template #label>
            <div class="user-container">
              <div class="text">基础信息</div>
            </div>
          </template>
          <div class="plane-con" style="width: 500px;">
            <el-form ref="ruleFormRef" :model="copyUserInfo" label-width="120px" :rules="detailRules" :size="formSize"
              status-icon>
              <el-form-item label="用户账号" prop="username">
                <el-input v-model="copyUserInfo.username" clearable />
              </el-form-item>
              <el-form-item label="用户昵称" prop="nickname">
                <el-input v-model="copyUserInfo.nickname" clearable />
              </el-form-item>
              <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="copyUserInfo.mobile" clearable />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="copyUserInfo.email" clearable />
              </el-form-item>
              <el-form-item label="所在地-省" prop="provinceCode">
                <el-select v-model="copyUserInfo.provinceCode" @change="proChange" placeholder="请选择所在省份" clearable>
                  <el-option v-for="item in province" :key="item.id" :label="item.dictItemName"
                    :value="item.dictItemCode" />
                </el-select>
              </el-form-item>
              <el-form-item label="所在地-市" prop="cityCode">
                <el-select v-model="copyUserInfo.cityCode" @change="proChange1" placeholder="请选择所在市" clearable>
                  <el-option v-for="item in selectProvinceCity" :key="item.id" :label="item.dictItemName"
                    :value="item.dictItemCode" />
                </el-select>
              </el-form-item>
              <el-form-item label="具体地址" prop="adress" clearable>
                <el-input v-model="copyUserInfo.adress" />
              </el-form-item>
              <el-form-item label="个人简介" prop="blurb" clearable>
                <el-input v-model="copyUserInfo.blurb" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane name="second">
          <template #label>
            <div class="user-container">
              <div class="text">安全设置</div>
            </div>
          </template>
          <div class="plane-con">
            <el-form label-width="120px" :model="passWordForm" :rules="passRules" ref="newPassRef">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input type="password" show-password v-model.trim="passWordForm.oldPassword" clearable></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input type="password" show-password v-model.trim="passWordForm.newPassword" clearable></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="newPasswordConfirm">
                <el-input type="password" show-password v-model="passWordForm.newPasswordConfirm" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button style="float: right;" @click="resetForm(newPassRef)">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

      </el-tabs>
    </el-card>
  </div>

</template>

<style lang='scss' scoped>
.card-style {
  // -top: 10px;

  .container {
  }
}

.user-container {

  border: none !important;
  color: #0D6DE2;
  text-align: center;
  line-height: 40px;
  height: 40px;
  padding: 0px 20px;
  cursor: pointer;
  border-radius: 5px;
}

/* 选中状态的样式 */
:deep(.el-tabs__item.is-active .user-container) {
  color: white;
  background-color: #0065E1;
}

// 鼠标悬停的样式
:deep(.el-tabs__item.is-hover .user-container) {
  border: 1px solid #CBE2FF;
  color: aqua;
}

/* 去掉tabs标签栏下的下划线 */
:deep(.el-tabs__nav-wrap::after) {
  position: static !important;
  /* background-color: #fff; */
}

/* 下划线修改 */
:deep(.el-tabs__active-bar) {
  background-color: transparent !important;
}

.line {
  color: #FF969DA6;
  height: 40px;
  line-height: 40px;
}

.line>span:last-child {
  color: black;
  margin-left: 10px;
}

.plane-con {
  height: 450px;
  width: 500px;
}
</style>
